package com.wo56.pushmsgcenter.common.utils;

import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import com.framework.core.util.impl.SysConfig;

public class HttpUtil {
	private static CloseableHttpClient client = null;
	private final static int INTF_TIMEOUT = 30000;
	public  final static String url = SysConfig.getConfigValueFromKey("send_url");

	static {
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(5);
		cm.setDefaultMaxPerRoute(5);
		client = HttpClients.custom().setConnectionManager(cm).build();
	}
	
	private static final Log log = LogFactory.getLog(HttpUtil.class);

	/**
	 * POST请求URL，传递JSON串参数
	 *
	 * @param url
	 * @param str
	 * @return
	 */
	public static String post(String url, String str) {
		HttpPost post = new HttpPost(url);
		String out = null;
		log.info("输入参数：" + str);
		try {

			StringEntity s = new StringEntity(str, "UTF-8");
			s.setContentEncoding("UTF-8");
			s.setContentType("application/xml");
			post.setEntity(s);
			// 设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(INTF_TIMEOUT).setConnectTimeout(2000)
					.build();
			post.setConfig(requestConfig);
			CloseableHttpResponse res = client.execute(post);
			if (res.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = res.getEntity();
				InputStream is = entity.getContent();
				out = IOUtils.toString(is, Consts.UTF_8);
				log.info("输出参数：" + out);
			} else {
				log.error("调用接口出错: " + out);
			}
			res.close();
		} catch (Exception e) {
			log.error("调用接口出错: " + e);
//			throw new RuntimeException(e);
		}
		return out;
	}
}
